package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.xxx.xbutler.data.RoomContactMapper;
import io.xxx.xbutler.data.RoomMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Room;
import io.xxx.xbutler.domain.RoomContact;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;

/**
 * 群成员退群回调
 * <p>
 * 群内有成员退群，通过该接口将成员退群信息回调给商家
 *
 * <pre>
 * {
 *     "nType": 4503,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": [
 *         {
 *             "nMemberCount": 10,
 *             "vcChatRoomId": "",
 *             "vcChatRoomSerialNo": "",
 *             "vcMemberUserWxId": "",
 *             "vcMemberUserSerialNo": "",
 *             "IsEnterpriseChatroom": false
 *         }
 *     ],
 *     "nTimeStamp": 1620700998101
 * }
 * </pre>
 */
@Slf4j
@Component
public class _4503Handler implements CallbackHandler {

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private RoomContactMapper roomContactMapper;

    @Override
    public String name() {
        return "群成员退群回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 4503;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        JSONObject data = (JSONObject) callback.getData();
        String roomId = data.getString("vcChatRoomId");

        LambdaUpdateWrapper<Room> roomWrapper = new LambdaUpdateWrapper<Room>()
                .set(Room::getMemberCount, data.getInteger("nMemberCount"))
                .set(Room::getUpdatedTime, now)
                .eq(Room::getId, roomId);
        LambdaUpdateWrapper<RoomContact> roomContactWrapper = new LambdaUpdateWrapper<RoomContact>()
                .set(RoomContact::getUpdatedTime, now)
                .eq(RoomContact::getRoomId, roomId)
                .eq(RoomContact::getContactId, data.getString("vcMemberUserWxId"));
        transactionTemplate.executeWithoutResult(_ -> {
            roomMapper.update(roomWrapper);
            roomContactMapper.delete(roomContactWrapper);
        });
    }
}
